<template>
  <div class="app-container">
    <div style="display: flex;flex-flow: row nowrap;margin-left: 10%;margin-bottom: 2%">
      <div style="border:1px;background-color: #4e8dff; width: 6px;height: 20px"></div>
      <span style="margin-left: 10px">{{ title }}</span>
    </div>
    <el-form v-loading="formLoading" ref="form" :model="form" :rules="rules" label-width="140px"
             style="margin-left: 25%;">
      <el-row>
        <el-col :span="16">
          <el-form-item v-if="deptList.length <2" label="考核部门" prop="deptName">
            <el-input v-model="deptName" disabled></el-input>
          </el-form-item>
          <el-form-item v-if="deptList.length >1" label="考核部门" prop="pickDeptId">
            <el-select v-model="deptIdTemp" placeholder="考核部门" style="width: 100%" @change="getPickDept">
              <el-option
                v-for="item in deptList"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="考核年度" prop="tempExamineYear">
            <el-date-picker
              v-model="form.tempExamineYear"
              type="year"
              placeholder="请选择考核年度"
              :picker-options="examineYearOptions"
              style="width: 100%"
              :disabled="isUpdate"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="考核周期" prop="examineCycle">
            <el-radio-group v-model="form.examineCycle" style="width: 120%" @change="radioChangeHandler"
                            :disabled="isUpdate">
              <el-radio
                v-for="dict in dict.type.examine_cycle"
                :key="dict.value"
                :label="dict.value"
              >{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="cycleVal==='month' && !isUpdate">
        <el-col :span="16">
          <el-form-item label="选择周期" prop="tempMonthPickCycle">
            <el-date-picker
              v-model="form.tempMonthPickCycle"
              type="month"
              placeholder="选择周期"
              style="width: 100%"
              format="yyyy 年 MM 月"
              :disabled="isUpdate"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="cycleVal==='quarter' && !isUpdate">
        <el-col :span="16">
          <el-form-item label="选择周期" prop="tempQuarterPickCycle">
            <quarter v-model="form.tempQuarterPickCycle" @change="getQuarter" :disabled="isUpdate"></quarter>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="cycleVal==='half_year' && !isUpdate">
        <el-col :span="16">
          <el-form-item label="选择周期" prop="tempHalfYearPickCycle">
            <halfyear v-model="form.tempHalfYearPickCycle" @change="getHalfyear" :disabled="isUpdate"></halfyear>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="cycleVal==='year' && !isUpdate">
        <el-col :span="16">
          <el-form-item label="选择周期" prop="tempExamineYear">
            <el-date-picker
              v-model="form.tempExamineYear"
              type="year"
              style="width: 100%"
              disabled
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isUpdate">
        <el-col :span="16">
          <el-form-item label="选择周期" required>
            <el-input v-model="form.pickCycleText" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <el-form-item label="附件" prop="attachFile">
            <file-upload v-model="form.attachFile"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="优秀人员">
        <el-row>
          <el-col :span="12">
            <div class="draggable">
              <draggable :disabled="isDisabled" v-model="data.excellentArray" group="site" animation="300"
                         dragClass="dragClass"
                         ghostClass="ghostClass"
                         chosenClass="chosenClass" @start="onStart" @end="onEnd">
                <transition-group class="draggable_area">
                  <div class="u-player" v-for="item in data.excellentArray" :key="item.userId">{{ item.userName }}</div>
                </transition-group>
              </draggable>
            </div>
          </el-col>
        </el-row>
        <span v-if="form.examineDeptId>0 && excellentNum>0" class="remarkText">根据激励规则计算，优秀人员最多选择 {{
            excellentNum
          }} 人</span>
        <span v-else class="remarkText">激励规则中优秀规则未配置，不限制选择人数</span>
      </el-form-item>
      <el-form-item label="良好人员">
        <el-row>
          <el-col :span="12">
            <div class="draggable">
              <draggable :disabled="isDisabled" v-model="data.goodArray" group="site" animation="300"
                         dragClass="dragClass"
                         ghostClass="ghostClass"
                         chosenClass="chosenClass" @start="onStart" @end="onEnd">
                <transition-group class="draggable_area">
                  <div class="u-player" v-for="item in data.goodArray" :key="item.userId">{{ item.userName }}</div>
                </transition-group>
              </draggable>
            </div>
          </el-col>
        </el-row>
        <span v-if="form.examineDeptId>0 && goodNum>0" class="remarkText">根据激励规则计算，良好人员最多选择 {{ goodNum }} 人</span>
        <span v-else class="remarkText">激励规则中良好规则未配置，不限制选择人数</span>
      </el-form-item>
      <el-form-item label="称职人员">
        <el-row>
          <el-col :span="12">
            <div class="draggable">
              <draggable :disabled="isDisabled" v-model="data.qualifiedArray" group="site" animation="300"
                         dragClass="dragClass"
                         ghostClass="ghostClass"
                         chosenClass="chosenClass" @start="onStart" @end="onEnd">
                <transition-group class="draggable_area">
                  <div class="u-player" v-for="item in data.qualifiedArray" :key="item.userId">{{ item.userName }}</div>
                </transition-group>
              </draggable>
            </div>
          </el-col>
        </el-row>
        <span v-if="form.examineDeptId>0 && qualifiedNum >0" class="remarkText">根据激励规则计算，称职人员最多选择 {{
            qualifiedNum
          }} 人</span>
        <span v-else class="remarkText">激励规则中称职规则未配置，不限制选择人数</span>
      </el-form-item>
      <el-form-item label="基本称职人员">
        <el-row>
          <el-col :span="12">
            <div class="draggable">
              <draggable :disabled="isDisabled" v-model="data.almostArray" group="site" animation="300"
                         dragClass="dragClass"
                         ghostClass="ghostClass"
                         chosenClass="chosenClass" @start="onStart" @end="onEnd">
                <transition-group class="draggable_area">
                  <div class="u-player" v-for="item in data.almostArray" :key="item.userId">{{ item.userName }}</div>
                </transition-group>
              </draggable>
            </div>
          </el-col>
        </el-row>
        <span v-if="form.examineDeptId>0 && almostNum >0" class="remarkText">根据激励规则计算，基本称职人员最多选择 {{
            almostNum
          }} 人</span>
        <span v-else class="remarkText">激励规则中基本称职规则未配置，不限制选择人数</span>
      </el-form-item>
      <el-form-item label="不称职人员">
        <el-row>
          <el-col :span="12">
            <div class="draggable">
              <draggable :disabled="isDisabled" v-model="data.unqualifiedArray" group="site" animation="300"
                         dragClass="dragClass"
                         ghostClass="ghostClass"
                         chosenClass="chosenClass" @start="onStart" @end="onEnd">
                <transition-group class="draggable_area">
                  <div class="u-player" v-for="item in data.unqualifiedArray" :key="item.userId">{{
                      item.userName
                    }}
                  </div>
                </transition-group>
              </draggable>
            </div>
          </el-col>
        </el-row>
        <span v-if=" form.examineDeptId>0 && unqualifiedNum >0" class="remarkText">根据激励规则计算，不称职人员最多选择 {{
            unqualifiedNum
          }} 人</span>
        <span v-else class="remarkText">激励规则中不称职规则未配置，不限制选择人数</span>
      </el-form-item>
    </el-form>
    <div style="margin: 2% auto auto 40%;">
      <el-button class="form_button_item" @click="closeBtnHandler">取消</el-button>
      <el-button class="form_button_item" :loading="saveBtnLoading" type="primary" @click="submitForm"
                 v-hasPermi="['examine:performance:add']">保存
      </el-button>
    </div>
  </div>
</template>

<script>
import draggable from "vuedraggable";
import quarter from "@/views/tool/quarter";
import halfyear from "@/views/tool/halfyear";
import {getUserDeptInfo} from "@/api/system/user";
import {treeselect} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import {getPerformance, addPerformance, updatePerformance} from "@/api/examine/performance/api";
import {listByType} from "@/api/system/rules/rulesApi";

export default {
  name: "Add",
  dicts: ['examine_cycle'],
  components: {
    quarter,
    halfyear,
    Treeselect,
    draggable
  },
  data() {
    return {
      deptIdTemp: '',
      isDisabled: false,
      formLoading: false,
      title: "",
      cycleVal: '',
      deptName: '',
      deptList: [],
      isUpdate: false,
      saveBtnLoading: false,
      // 表单参数
      form: {pickDeptId: ''},
      examineId: '',
      // 部门树选项
      deptOptions: [],
      // 表单校验
      rules: {
        tempExamineYear: [
          {required: true, message: "请选择考核年度", trigger: "change"}
        ],
        examineCycle: [
          {required: true, message: "请选择考核周期", trigger: "change"}
        ],
        tempMonthPickCycle: [
          {required: true, message: "请选择周期", trigger: "change"}
        ],
        tempQuarterPickCycle: [
          {required: true, message: "请选择周期", trigger: "change"}
        ],
        tempHalfYearPickCycle: [
          {required: true, message: "请选择周期", trigger: "change"}
        ],
        pickDeptId: [
          {required: true, message: "请选择考核部门", trigger: "change"}
        ],
        attachFile: [
          {required: true, message: "请上传附件", trigger: "blur"}
        ],
      },
      examineYearOptions: {
        disabledDate: (time) => {
          const date = new Date()
          const year = date.getFullYear()
          const timeYear = time.getFullYear()
          return year > timeYear + 3
        }
      },
      excellentNum: 1,
      goodNum: 1,
      almostNum: 1,
      qualifiedNum: 1,
      unqualifiedNum: 1,
      data: {
        excellentArray: [],
        goodArray: [],
        almostArray: [],
        qualifiedArray: [],
        unqualifiedArray: []
      },
      pickPerson: {},
      allNumLength: 0
    }
  },
  created() {
    this.initPage();
  },
  methods: {
    initPage() {
      this.reset()
      this.getTreeselect()
      this.examineId = this.$route.query.id;
      if (this.examineId) {
        this.title = '编辑考核'
        this.isUpdate = true;
        this.formLoading = true;
        getPerformance(this.examineId).then(resp => {
          this.form.id = this.examineId
          this.data.excellentArray = resp.data.excellentPersonList
          this.data.goodArray = resp.data.goodPersonList
          this.data.almostArray = resp.data.almostPersonList
          this.data.qualifiedArray = resp.data.qualifiedPersonList
          this.data.unqualifiedArray = resp.data.unqualifiedPersonList
          this.allNumLength = resp.data.excellentPersonList.length + resp.data.goodPersonList.length + resp.data.qualifiedPersonList.length + resp.data.unqualifiedPersonList.length + resp.data.almostPersonList.length
          if (resp.data.attachFile) {
            this.form.attachFile = resp.data.attachFile
          }
          this.getExamineRules();
          if (resp.data.ancestorNames) {
            this.deptName = resp.data.ancestorNames
          } else {
            this.deptName = '中层管理考核'
          }
          this.$set(this.form, 'pickCycleText', resp.data.pickCycleText)
          this.$set(this.form, 'examineDeptId', resp.data.examineDeptId)
          this.$set(this.form, 'tempExamineYear', resp.data.examineYear)
          this.$set(this.form, 'examineCycle', resp.data.examineCycle)
          this.cycleVal = resp.data.examineCycle
          if (resp.data.examineCycle === 'month') {
            this.$set(this.form, 'tempMonthPickCycle', resp.data.pickCycle)
          } else if (resp.data.examineCycle === 'quarter') {
            this.$set(this.form, 'tempQuarterPickCycle', resp.data.pickCycle)
          } else if (resp.data.examineCycle === 'half_year') {
            this.$set(this.form, 'tempHalfYearPickCycle', resp.data.pickCycle)
          }
        }).finally(() => {
          this.formLoading = false;
        })
      } else {
        this.title = '提交考核'
        // 考核年度默认当前年
        this.$set(this.form, 'tempExamineYear', String(new Date().getFullYear()))
        getUserDeptInfo().then(resp => {
          this.deptList = resp.data.deptList;
          if (resp.data.deptList.length === 1) {
            this.form.examineDeptId = this.deptList[0].deptId
            this.deptName = this.deptList[0].deptName
          }
          this.pickPerson = resp.data.dataAuthDeptList;
          this.deptIdTemp = Number(Object.keys(resp.data.dataAuthDeptList)[0])
          this.form.examineDeptId = Object.keys(resp.data.dataAuthDeptList)[0];
          // this.form.pickDeptId=this.deptIdTemp;
          this.getPickDept(Object.keys(resp.data.dataAuthDeptList)[0]);
        })
      }
    },
    getPickDept(val) {
      this.data.excellentArray = []
      this.data.goodArray = []
      this.data.almostArray = []
      this.data.qualifiedArray = []
      this.data.unqualifiedArray = []
      // this.deptIdTemp=val;
      this.form.examineDeptId = val;
      this.form.pickDeptId = val;
      this.data.unqualifiedArray = this.pickPerson[val];
      this.allNumLength = this.pickPerson[val].length;
      this.getExamineRules();
    },
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.tempExamineYear instanceof Date) {
            // 不是默认值 日期类型做字符串处理
            this.form.examineYear = this.form.tempExamineYear.getFullYear()
          } else {
            this.form.examineYear = this.form.tempExamineYear
          }
          if (this.cycleVal === 'month') {
            this.form.pickCycle = this.form.tempMonthPickCycle
            this.form.pickCycleText = new Date(this.form.tempMonthPickCycle).getFullYear() + '年 ' + (new Date(this.form.tempMonthPickCycle).getMonth() + 1) + '月'
          } else if (this.cycleVal === 'quarter') {
            this.form.pickCycle = this.form.tempQuarterPickCycle
          } else if (this.cycleVal === 'half_year') {
            this.form.pickCycle = this.form.tempHalfYearPickCycle
          }
          // 年度选择周期转换值
          if (this.cycleVal === 'year') {
            this.form.pickCycle = new Date(String(this.form.examineYear) + '-01-01')
            this.form.pickCycleText = new Date(String(this.form.examineYear) + '-01-01').getFullYear() + '年'
          }
          var dragArr = this.data;
          if (dragArr) {
            if (dragArr.excellentArray) {
              this.form.excellentPersonIds = dragArr.excellentArray.map(m => m.userId)
            }
            if (dragArr.goodArray) {
              this.form.goodPersonIds = dragArr.goodArray.map(m => m.userId)
            }
            if (dragArr.almostArray) {
              this.form.almostPersonIds = dragArr.almostArray.map(m => m.userId)
            }
            if (dragArr.qualifiedArray) {
              this.form.qualifiedPersonIds = dragArr.qualifiedArray.map(m => m.userId)
            }
            if (dragArr.unqualifiedArray) {
              this.form.unqualifiedPersonIds = dragArr.unqualifiedArray.map(m => m.userId)
            }
          }
          if (new Date(this.form.pickCycle).getFullYear() != this.form.examineYear) {
            this.$modal.msgError("考核年度与选择周期中年份不一致，请重新选择周期");
            return;
          }
          this.saveBtnLoading = true;
          if (this.form.id != null) {
            updatePerformance(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              // 清空页签缓存
              this.$tab.clearKeepAlivePage('Index')
              this.closeBtnHandler();
            }).finally(() => {
              this.saveBtnLoading = false;
            })
          } else {
            addPerformance(this.form).then(response => {
              this.$modal.msgSuccess("提交成功");
              // 清空页签缓存
              this.$tab.clearKeepAlivePage('Index')
              this.closeBtnHandler();
            }).finally(() => {
              this.saveBtnLoading = false;
            })
          }
        }
      });
    },
    closeBtnHandler() {
      this.reset()
      // 关闭当前页面
      this.$tab.closeOpenPage();
      // 刷新列表页面
      this.$tab.refreshPage({path: "/examine/index"});
    },
    // 季度选择回调
    getQuarter(val, text) {
      this.form.tempQuarterPickCycle = val
      this.form.pickCycleText = text
    },
    // 半年度选择回调
    getHalfyear(val, text) {
      this.form.tempHalfYearPickCycle = val
      this.form.pickCycleText = text
    },
    radioChangeHandler(data) {
      this.cycleVal = data;
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        examineDeptName: undefined,
        examineDeptId: undefined,
        pickCycleText: undefined,
        tempExamineYear: undefined,
        examineCycle: undefined,
        tempMonthPickCycle: undefined,
        tempQuarterPickCycle: undefined,
        tempHalfYearPickCycle: undefined,
        attachFile: undefined
      };
      this.resetForm("form");
    },
    getExamineRules() {
      // 绩效考核规则取配置
      listByType(0).then(rulesResp => {
        // 查询优秀最多可加入人数
        var excellentRules = rulesResp.rows.filter(f => f.status == 3);
        if (excellentRules.length > 0 && excellentRules[0].personScale) {
          this.excellentNum = (excellentRules[0].personScale / 100 * this.allNumLength).toFixed(0) > 0 ? (excellentRules[0].personScale / 100 * this.allNumLength).toFixed(0) : 1
        } else {
          this.excellentNum = -1;
        }
        // 查询良好最多可加入人数
        var goodRules = rulesResp.rows.filter(f => f.status == 2);
        if (goodRules && goodRules[0].personScale) {
          this.goodNum = (goodRules[0].personScale / 100 * this.allNumLength).toFixed(0) > 0 ? (goodRules[0].personScale / 100 * this.allNumLength).toFixed(0) : 1
        } else {
          this.goodNum = -1;
        }

        // 查询基本称职最多可加入人数
        var almostRules = rulesResp.rows.filter(f => f.status == 4);
        if (almostRules && almostRules[0].personScale) {
          this.almostNum = (almostRules[0].personScale / 100 * this.allNumLength).toFixed(0) > 0 ? (almostRules[0].personScale / 100 * this.allNumLength).toFixed(0) : 1
        } else {
          this.almostNum = -1;
        }

        // 查询称职最多可加入人数
        var qualifiedRules = rulesResp.rows.filter(f => f.status == 1);
        if (qualifiedRules.length > 0 && qualifiedRules[0].personScale) {
          this.qualifiedNum = (qualifiedRules[0].personScale / 100 * this.allNumLength).toFixed(0) > 0 ? (qualifiedRules[0].personScale / 100 * this.allNumLength).toFixed(0) : 1
        } else {
          this.qualifiedNum = -1;
        }
        // 查询称职最多可加入人数
        var unqualifiedRules = rulesResp.rows.filter(f => f.status == 0);
        if (unqualifiedRules.length > 0 && unqualifiedRules[0].personScale) {
          this.unqualifiedNum = (unqualifiedRules[0].personScale / 100 * this.allNumLength).toFixed(0) > 0 ? (unqualifiedRules[0].personScale / 100 * this.allNumLength).toFixed(0) : 1
        } else {
          this.unqualifiedNum = -1;
        }
      })
    },
    onStart() {
      this.drag = true;
    },
    onEnd() {
      this.drag = false;
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #fff;
  color: #606266;
}

::v-deep .el-textarea.is-disabled .el-textarea__inner {
  background-color: #fff;
  color: #606266;
}

::v-deep .el-radio__input.is-disabled + span.el-radio__label {
  background-color: #fff;
  color: #606266;
}

.draggable {
  width: 600px;
  height: 150px;
  border: solid 1px #eee;
  border-radius: 5px;

  .u-player {
    margin-top: 10px;
    margin-left: 10px;
    display: inline-block;
    color: #0079DD;
    background: #F0F7FD;
    font-size: 14px;
    font-weight: 400;
    padding: 3px 5px;
    border-radius: 6px;
    cursor: move;

    &:not(:last-child) {
      //margin-right: 16px;
    }
  }
}

// 拖拽默认空间
.draggable_area {
  min-height: 120px;
  display: block;
}

.chosen { // 选择元素的样式
  background: #666 !important;
  color: #fff !important;
}

.el-form-item__content {
  line-height: unset !important;
}

.ghost { // 目标位置占位符的样式及需要停靠位置的样式
  background: #1890FF !important;
}

.remarkText {
  font-size: 12px;
  color: #AAAAAA;
}
</style>
